% 1. Inverse stroke image and calculate superpixels segmentation
function colors = findBaseColors(im)

colors = [];

addpath('D:\Projects\Thesis\matlab\vlfeat-master\toolbox');
vl_setup;

im = double(im) / 255;

iim = 1 - im;
iim = im;

figure(1);
imshow(iim);
title('original inverse image');

disp('running superpixels');

if(1)
    segments = vl_slic(single(iim), 10, 0.05);
    save('segments.mat', 'segments');
else
    s = load('segments.mat');
    segments = s.segments;
end

disp('done');

lblImg = double(segments);
[gx,gy] = gradient(lblImg);
lblImg((gx.^2+gy.^2)==0) = 0;


inds = lblImg > 0;
im2 = im;
im2(repmat(inds,[1,1,3])) = 1;

figure(2);
imshow(im2,[]);
title('segmented image');

% 2. Calculate the mean colors of an image according the segments image
L = segments;
numLabels=max(L(:)); % L is the Label matrix
STATS=regionprops(L,'pixelIdxList');
im1=iim(:,:,1);
im2=iim(:,:,2);
im3=iim(:,:,3);
MeanColors=zeros(numLabels,3);

numLabels

for i=1:numLabels
    MeanColors(i,1) = mean(im1(STATS(i).PixelIdxList));
    MeanColors(i,2) = mean(im2(STATS(i).PixelIdxList));
    MeanColors(i,3) = mean(im3(STATS(i).PixelIdxList));
end


% Scatter plot each super pixel
figure(3);
hold off;
scatter3(MeanColors(:,1), MeanColors(:,2), MeanColors(:,3), 50, MeanColors, 'filled');


% Greedy selection of base colors, i.e 

% Clip color spec:
min_thresh = 0.2;
max_thresh = 1.5;
norm = sqrt(sum(MeanColors .* MeanColors,2));
inds =  norm > min_thresh & norm < max_thresh;
mc = MeanColors(inds,:);
% hold on;
% scatter3(mc(:,1), mc(:,2), mc(:,3), 70, [1 0 1]);
% title('scatter of mean colors and');

colors = mc;

figure(4);
hold off;
scatter3(colors(:,1), colors(:,2), colors(:,3), 50, colors, 'filled');





